using System.Collections.Generic;
using System.IO;
using System.Linq;
using QGameFramework.SO;
using UnityEditor;
using UnityEditor.U2D;
using UnityEngine;
using UnityEngine.U2D;

namespace QGameFramework.Editors
{
    public class AtlasGenerator : EditorWindow
    {
        private AlatsPathSO alatsPathSO;

        [MenuItem("PnTool/Atlas Generator &S")]
        public static void ShowWindow()
        {
            GetWindow<AtlasGenerator>("Atlas Generator");
        }

        void OnGUI()
        {
            EditorGUILayout.BeginVertical();

            alatsPathSO = (AlatsPathSO)EditorGUILayout.ObjectField("Alats Path SO:", alatsPathSO, typeof(AlatsPathSO), false);
            if (GUILayout.Button("Scan Sprites"))
            {
                ScanImages();
            }

            if (GUILayout.Button("Generate Atlases"))
            {
                GenerateAtlases();
            }

            EditorGUILayout.EndVertical();
        }

        /// <summary>
        /// 扫描图片
        /// </summary>
        void ScanImages()
        {
            if (alatsPathSO == null)
            {
                Debug.LogError("AlatsPathSO is not specified.");
                return;
            }

            string fullPath = Application.dataPath + alatsPathSO.AlatsClectionPath;

            var imagesPaths = Directory.GetFiles(fullPath, "*.*", SearchOption.AllDirectories);
            alatsPathSO.ElementFloder.Clear();

            foreach (var imagePath in imagesPaths)
            {
                if (imagePath.EndsWith(".png") || imagePath.EndsWith(".jpg"))
                {
                    var imgs = new Imgs();
                    imgs.ImgsPath = new List<Img> { new Img { path = imagePath } };
                    alatsPathSO.ElementFloder.Add(imgs);
                }
            }

            EditorUtility.SetDirty(alatsPathSO);
            AssetDatabase.SaveAssets();
            Debug.Log("Images scanning and saving complete.");
        }

        void GenerateAtlases()
        {
            if (alatsPathSO == null)
            {
                Debug.LogError("AlatsPathSO is not specified.");
                return;
            }

            alatsPathSO.Alats.Clear(); // 清空当前图集列表，准备重新收集

            foreach (var imgGroup in alatsPathSO.ElementFloder)
            {
                if (imgGroup.ImgsPath.Count == 0) continue; // 如果当前分组无图片，则跳过此次循环

                string atlasName = Path.GetFileName(Path.GetDirectoryName(imgGroup.ImgsPath[0].path));
                string atlasAssetPath = Path.Combine(alatsPathSO.AlatsSavePath, atlasName + ".spriteatlas");

                // 检查图集是否已存在，若存在则进行载入而非重新创建
                SpriteAtlas atlas = AssetDatabase.LoadAssetAtPath<SpriteAtlas>(atlasAssetPath);
                if (atlas == null)
                {
                    atlas = new SpriteAtlas();
                    AssetDatabase.CreateAsset(atlas, atlasAssetPath);
                }

                Object[] packedObjects = atlas.GetPackables();


                foreach (var img in imgGroup.ImgsPath)
                {
                    string relativePath = "Assets" + img.path.Substring(Application.dataPath.Length); // 构建Unity资源相对路径
                    Texture2D texture = AssetDatabase.LoadAssetAtPath<Texture2D>(relativePath);

                    if (texture != null && !packedObjects.Contains(texture))
                    {
                        // 将Texture2D添加到图集
                        SpriteAtlasExtensions.Add(atlas, new Object[] { texture }); // Unity 2017.1以上支持此API
                    }
                }

                alatsPathSO.Alats.Add(atlas); // 将更新后的图集添加到列表中
            }

            EditorUtility.SetDirty(alatsPathSO);
            AssetDatabase.SaveAssets(); // 保存所有未保存的资产更改

            Debug.Log("Atlas generation complete.");
        }
    }
}